package com.lecoboy.highconcurrency.atomicdemo;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 原子更新引用类型 示例
 */
public class AtomicReferenceTest {
    public static AtomicReference<User> atomicReference = new AtomicReference<>();

    public static void main(String[] args) {
        /**
         * 首先构建一个user对象，然后把user对象设置进AtomicReferenc中，
         * 最后调用compareAndSet方法进行原子更新操作，实现原理同AtomicInteger里的compareAndSet方法。
         */
        User user = new User("conan", 15);
        atomicReference.set(user);
        User updateUser = new User("Shinichi", 17);
        atomicReference.compareAndSet(user, updateUser);
        /**
         *         正确输出
         *         Shinichi
         *         17
         */
        System.out.println(atomicReference.get().getName());
        System.out.println(atomicReference.get().getOld());

    }
    static class User {
        private String name;
        private int old;

        public User(String name, int old) {
            this.name = name;
            this.old = old;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getOld() {
            return old;
        }

        public void setOld(int old) {
            this.old = old;
        }
    }
}
